import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:flutter_swiper_view/flutter_swiper_view.dart';

import 'package:get/get.dart';
import 'package:xiaomi_shop/app/api/api.dart';
import 'package:xiaomi_shop/app/services/iconWrapper.dart';
import 'package:xiaomi_shop/app/services/keepAliveWrapper.dart';
import 'package:xiaomi_shop/app/services/screenAdapter.dart';
import 'package:xiaomi_shop/models/index.dart';

import '../controllers/home_controller.dart';

class HomeView extends GetView<HomeController> {
  const HomeView({Key? key}) : super(key: key);

  Widget _appBar() {
    return Positioned(
        top: 0,
        left: 0,
        right: 0,
        child: Obx(
          () => AppBar(
            leading: controller.isTop.value
                ? Icon(
                    IconWrapper.xiaomi,
                    color: Colors.white,
                    size: ScreenAdapter.width(80),
                  )
                : const Text(""),
            leadingWidth: controller.isTop.value
                ? ScreenAdapter.width(140)
                : ScreenAdapter.width(40),
            centerTitle: true,
            title: AnimatedContainer(
              duration: const Duration(milliseconds: 600),
              decoration: BoxDecoration(
                  color: controller.isTop.value
                      ? Color.fromARGB(230, 255, 255, 255)
                      : Color.fromARGB(230, 246, 246, 246),
                  borderRadius:
                      BorderRadius.circular(ScreenAdapter.height(50))),
              width: controller.isTop.value
                  ? ScreenAdapter.width(640)
                  : ScreenAdapter.width(800),
              height: ScreenAdapter.height(100),
              child: InkWell(
                onTap: () => Get.toNamed('/search'),
                child: Row(
                  children: [
                    Padding(
                      padding: EdgeInsets.fromLTRB(ScreenAdapter.width(34), 0,
                          ScreenAdapter.width(16), 0),
                      child: const Icon(
                        Icons.search,
                        color: Colors.black26,
                      ),
                    ),
                    Text(
                      "手机",
                      style: TextStyle(
                          color: Colors.black26,
                          fontSize: ScreenAdapter.fontSize(36)),
                    )
                  ],
                ),
              ),
            ),
            backgroundColor:
                controller.isTop.value ? Colors.transparent : Colors.white,
            scrolledUnderElevation: 0,
            actions: [
              IconButton(
                  onPressed: () {},
                  icon: Icon(
                    Icons.qr_code,
                    color:
                        controller.isTop.value ? Colors.white : Colors.black87,
                    size: ScreenAdapter.width(64),
                  )),
              IconButton(
                  onPressed: () {},
                  icon: Icon(
                    Icons.message_outlined,
                    color:
                        controller.isTop.value ? Colors.white : Colors.black87,
                    size: ScreenAdapter.width(64),
                  ))
            ],
          ),
        ));
  }

  // 轮播图
  Widget _banner() {
    return SizedBox(
      height: ScreenAdapter.height(740),
      child: Obx(() => Swiper(
            itemCount: controller.swiperList.value.length,
            itemBuilder: (context, index) {
              var src =
                  "${Api.basicUrl}/${controller.swiperList.value[index].pic}";
              return Image.network(
                src,
                fit: BoxFit.fill,
              );
            },
            autoplay: true,
            loop: true,
            pagination: const SwiperPagination(builder: SwiperPagination.rect),
            onTap: (index) {
              Get.toNamed('/shopDetail',
                  arguments: {"id": controller.swiperList.value[index].id});
            },
          )),
    );
  }

  // 服务说明
  Widget _serviceTip() {
    return SizedBox(
      width: ScreenAdapter.width(1080),
      height: ScreenAdapter.height(92),
      child: Image.asset(
        "assets/images/xiaomiBanner.png",
        fit: BoxFit.cover,
      ),
    );
  }

  // 商品分类
  Widget _shopCategory() {
    return SizedBox(
        width: ScreenAdapter.width(1080),
        height: ScreenAdapter.height(470),
        child: Obx(() {
          // 如果求余=0，说明可以整除，页数为除数，求余!=0,不能整除，页数为除数+1
          int page = controller.shopCategoryList.length % 10 == 0
              ? controller.shopCategoryList.length ~/ 10
              : controller.shopCategoryList.length ~/ 10 + 1;
          return Swiper(
            itemCount: page,
            autoplay: false,
            loop: false,
            itemBuilder: (context, index) {
              // 如果可以整除，每页10个元素。如果不能整除，最后一页元素个数为余数，前面每页10个元素
              int itemCount = controller.shopCategoryList.length % 10 == 0
                  ? 10
                  : ((index + 1) < page
                      ? 10
                      : controller.shopCategoryList.length % 10);
              return GridView.builder(
                padding: EdgeInsets.fromLTRB(
                    ScreenAdapter.width(20), 0, ScreenAdapter.width(20), 0),
                physics: const NeverScrollableScrollPhysics(),
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount:
                        5, // 一行是5个，所以item 的宽度已经固定， 高度根据设置的比例 childAspectRatio 计算
                    mainAxisSpacing: ScreenAdapter.height(20),
                    crossAxisSpacing: ScreenAdapter.width(20),
                    childAspectRatio: 0.9),
                itemCount: itemCount,
                itemBuilder: (context, i) {
                  ShopCategoryModel cateModel =
                      controller.shopCategoryList.value[i + index * 10];
                  return InkWell(
                      onTap: () {
                        Get.toNamed('/shop',
                            parameters: {"cid": cateModel.id!});
                      },
                      child: Column(
                        children: [
                          Container(
                            alignment: Alignment.center,
                            width: ScreenAdapter.width(140),
                            height: ScreenAdapter.width(140),
                            child: Image.network(
                              "${Api.basicUrl}/${cateModel.pic}",
                              fit: BoxFit.fitHeight,
                            ),
                          ),
                          Padding(
                            padding: EdgeInsets.fromLTRB(
                                0, ScreenAdapter.height(8), 0, 0),
                            child: Text(
                              "${cateModel.title}",
                              style: TextStyle(
                                  fontSize: ScreenAdapter.fontSize(32)),
                            ),
                          ),
                        ],
                      ));
                },
              );
            },
            pagination: SwiperPagination(
                margin: const EdgeInsets.all(0),
                builder: SwiperCustomPagination(
                  builder: (context, config) {
                    return ConstrainedBox(
                        constraints: BoxConstraints.expand(
                            height: ScreenAdapter.height(20)),
                        child: Row(
                          children: [
                            Expanded(
                                child: Align(
                                    alignment: Alignment.center,
                                    child: const RectSwiperPaginationBuilder(
                                            color: Colors.black26,
                                            activeColor: Colors.black45,
                                            space: 0)
                                        .build(context, config))),
                          ],
                        ));
                  },
                )),
          );
        }));
  }

  // 热销甄选
  Widget _hotShop() {
    return Container(
      width: ScreenAdapter.width(1080),
      height: ScreenAdapter.height(850),
      padding: EdgeInsets.fromLTRB(
          ScreenAdapter.width(30), 0, ScreenAdapter.width(30), 0),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text("热销甄选",
                  style: TextStyle(
                      fontSize: ScreenAdapter.fontSize(48),
                      fontWeight: FontWeight.bold)),
              TextButton(
                  style: const ButtonStyle(
                      foregroundColor: MaterialStatePropertyAll(Colors.black54),
                      padding: MaterialStatePropertyAll(EdgeInsets.zero)),
                  onPressed: () {},
                  child: const Row(
                    children: [Text("更多手机推荐"), Icon(Icons.navigate_next)],
                  ))
            ],
          ),
          Expanded(
            flex: 1,
            child: Obx(() => Row(
                  children: [
                    SizedBox(
                      width: ScreenAdapter.width(500),
                      child: Swiper(
                        itemCount: controller.hotShopBannerList.length,
                        itemBuilder: (context, index) {
                          return Image.network(
                            "${Api.basicUrl}/${controller.hotShopBannerList.value[index].pic!}",
                            fit: BoxFit.fill,
                          );
                        },
                        autoplay: true,
                        pagination: const SwiperPagination(
                            builder: SwiperPagination.rect),
                        onTap: (index) {
                          Get.toNamed('/shopDetail', arguments: {
                            "id": controller.hotShopBannerList.value[index].id
                          });
                        },
                      ),
                    ),
                    SizedBox(
                      width: ScreenAdapter.width(20),
                    ),
                    Expanded(
                        child: Column(
                            children: controller.hotShopList.value
                                .asMap()
                                .entries
                                .map((e) {
                      ShopModel model = e.value;
                      print(model.title);
                      return Expanded(
                          child: InkWell(
                              onTap: () {
                                Get.toNamed('/shopDetail',
                                    arguments: {"id": model.id});
                              },
                              child: Container(
                                margin: EdgeInsets.fromLTRB(0, 0, 0,
                                    e.key == 2 ? 0 : ScreenAdapter.height(20)),
                                padding:
                                    EdgeInsets.all(ScreenAdapter.height(20)),
                                decoration: BoxDecoration(
                                    color: Color.fromARGB(255, 245, 245, 245),
                                    borderRadius: BorderRadius.circular(
                                        ScreenAdapter.width(16))),
                                child: Row(
                                  children: [
                                    Expanded(
                                        child: Column(
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        Text(
                                          model.title!,
                                          style: TextStyle(
                                              fontWeight: FontWeight.bold,
                                              fontSize:
                                                  ScreenAdapter.fontSize(36)),
                                        ),
                                        SizedBox(
                                          height: ScreenAdapter.height(8),
                                        ),
                                        Text(
                                          model.sub_title!,
                                          style: TextStyle(
                                              fontSize:
                                                  ScreenAdapter.fontSize(28)),
                                        ),
                                        SizedBox(
                                          height: ScreenAdapter.height(8),
                                        ),
                                        Text(
                                          "¥ ${model.price}",
                                          style: TextStyle(
                                              fontSize:
                                                  ScreenAdapter.fontSize(28),
                                              fontWeight: FontWeight.bold),
                                        ),
                                      ],
                                    )),
                                    Image.network(
                                      "${Api.basicUrl}/${model.pic}",
                                      fit: BoxFit.cover,
                                    ),
                                  ],
                                ),
                              )));
                    }).toList()))
                  ],
                )),
          )
        ],
      ),
    );
  }

  Widget _bestShopList() {
    return Container(
        width: ScreenAdapter.width(1080),
        padding: EdgeInsets.fromLTRB(
            ScreenAdapter.width(30), 0, ScreenAdapter.width(30), 0),
        child: Column(children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text("省心优惠",
                  style: TextStyle(
                      fontSize: ScreenAdapter.fontSize(48),
                      fontWeight: FontWeight.bold)),
              TextButton(
                  style: const ButtonStyle(
                      foregroundColor: MaterialStatePropertyAll(Colors.black54),
                      padding: MaterialStatePropertyAll(EdgeInsets.zero)),
                  onPressed: () {},
                  child: const Row(
                    children: [Text("全部优惠"), Icon(Icons.navigate_next)],
                  ))
            ],
          ),
          Obx(() =>
              // 瀑布流商品列表
              MasonryGridView.count(
                crossAxisCount: 2,
                mainAxisSpacing: ScreenAdapter.width(20),
                crossAxisSpacing: ScreenAdapter.width(20),
                itemCount: controller.bestShopList.length,
                physics: const NeverScrollableScrollPhysics(),
                shrinkWrap: true, // 元素根据实际内容设置大小
                itemBuilder: (context, index) {
                  ShopModel model = controller.bestShopList.value[index];
                  return InkWell(
                    onTap: () {
                      Get.toNamed('/shopDetail', arguments: {"id": model.id});
                    },
                    child: Container(
                      padding: EdgeInsets.all(ScreenAdapter.width(20)),
                      decoration: BoxDecoration(
                          color: const Color.fromRGBO(246, 246, 246, 1),
                          borderRadius:
                              BorderRadius.circular(ScreenAdapter.width(16))),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Image.network("${Api.basicUrl}/${model.s_pic}"),
                          SizedBox(
                            height: ScreenAdapter.height(16),
                          ),
                          Text(
                            model.title!,
                            style: TextStyle(
                                fontSize: ScreenAdapter.fontSize(38),
                                fontWeight: FontWeight.bold,
                                overflow: TextOverflow.ellipsis),
                            maxLines: 2,
                          ),
                          Text(
                            model.sub_title!,
                            style: TextStyle(
                                fontSize: ScreenAdapter.fontSize(30),
                                overflow: TextOverflow.ellipsis),
                            maxLines: 1,
                          ),
                          Text("¥ ${model.price}",
                              style: TextStyle(
                                  fontSize: ScreenAdapter.fontSize(38),
                                  fontWeight: FontWeight.bold)),
                        ],
                      ),
                    ),
                  );
                },
              ))
        ]));
  }

  // 先绘制ListView 再绘制Appbar
  Widget _homeContent() {
    return Positioned(
      top: -ScreenUtil().statusBarHeight,
      left: 0,
      bottom: 0,
      right: 0,
      child: ListView(
        controller: controller.scrollController,
        children: [
          _banner(),
          _serviceTip(),
          _shopCategory(),
          _hotShop(),
          _bestShopList(),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return KeepAliveWrapper(
      child: Scaffold(
          // 这里不能使用 Scaffold 中的 appBar。
          body: Stack(
        children: [_homeContent(), _appBar()],
      )),
    );
  }
}
